package com.jwsoft.manager.core.integration.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bifang.assistant.common.vo.BaseVO;
import com.bifang.engine.assistant.core.annotation.ApiService;
import com.bifang.engine.assistant.core.annotation.OpApi;
import com.bifang.engine.assistant.core.annotation.SaveOplog;
import com.bifang.engine.assistant.core.enums.AuTypeEnum;
import com.bifang.engine.assistant.core.enums.BoolEnum;
import com.bifang.engine.assistant.core.enums.FuncTypeEnum;
import com.bifang.engine.assistant.core.exception.AppException;
import com.bifang.engine.assistant.core.utils.SessionUtil;
import com.bifang.engine.data.core.util.PagerUtil;
import com.bifang.module.base.common.vo.operationPeriod.OperationCurVO;
import com.bifang.module.base.common.vo.operationPeriod.OperationPeriodVO;
import com.bifang.module.base.core.helper.DictHelper;
import com.bifang.module.base.core.integration.OperationPeriodIntegration;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jwsoft.manager.common.enums.SchoolDictEnum;
import com.jwsoft.manager.common.vo.eduUnionSchool.EduUnionSchoolKeyVO;
import com.jwsoft.manager.common.vo.eduUnionSchool.EduUnionSchoolQueryVO;
import com.jwsoft.manager.common.vo.eduUnionSchool.EduUnionSchoolVO;
import com.jwsoft.manager.common.vo.eduUnionSchoolDetail.EduUnionSchoolDetailKeyVO;
import com.jwsoft.manager.core.dao.model.EduUnionSchool;
import com.jwsoft.manager.core.dao.model.EduUnionSchoolDetail;
import com.jwsoft.manager.core.dao.service.EduUnionSchoolDetailService;
import com.jwsoft.manager.core.dao.service.EduUnionSchoolService;
import com.jwsoft.manager.core.integration.EduUnionSchoolIntegration;
import com.jwsoft.manager.core.util.EduHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

/**
 * 户籍跨校联合区表业务实现类
 *
 * @author wangtao
 * @since 2022-12-22
 */
@ApiService(funcCode = "eduUnionSchool", title = "户籍跨校联合区表")
public class EduUnionSchoolIntegrationImpl implements EduUnionSchoolIntegration {

    @Autowired
    public EduUnionSchoolService eduUnionSchoolService;

    @Autowired
    public DictHelper dictHelper;
    @Autowired
    private EduHelper eduHelper;

    @Resource
    public OperationPeriodIntegration operationPeriodIntegration;

    @Autowired
    public EduUnionSchoolDetailService eduUnionSchoolDetailService;

    @Override
    @OpApi(funcCode = "eduUnionSchool0001", title = "户籍跨校联合区表分页查询", funcType = FuncTypeEnum.query)
    public PageInfo<EduUnionSchoolVO> getList(EduUnionSchoolQueryVO vo) {
        // 开启分页
        if (vo.getPageNum() == null || vo.getPageSize() == null) {
            //如果不传入分页参数，默认最大取1000条
            vo.setPageNum(1);
            vo.setPageSize(1000);
        }
        PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
        QueryWrapper<EduUnionSchool> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().select(EduUnionSchool::getUnionSchoolName,
                EduUnionSchool::getYear, EduUnionSchool::getHighFlag,
                EduUnionSchool::getRemark, EduUnionSchool::getUnionSchoolId,
                EduUnionSchool::getAreaCode);
        if (vo.getYear() != null) {
            queryWrapper.lambda().eq(EduUnionSchool::getYear, vo.getYear());
        }
        if (StringUtils.isNotBlank(vo.getUnionSchoolName())) {
            queryWrapper.lambda().eq(EduUnionSchool::getUnionSchoolName, vo.getUnionSchoolName());
        }
        if (StringUtils.isNotBlank(vo.getAreaCode())) {
            queryWrapper.lambda().eq(EduUnionSchool::getAreaCode, vo.getAreaCode());
        }
        List<EduUnionSchool> list = eduUnionSchoolService.list(queryWrapper);
        if (CollectionUtils.isEmpty(list)) {
            // 判断是否为空，为空则返回空参数
            return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
        }
        // 不为空则获取分页结果
        PageInfo<EduUnionSchool> pageInfo = new PageInfo<>(list);
        // 返回参数需要通过common层的vo实体类，用该方法可以批量转换
        List<EduUnionSchoolVO> resultList = Convert.toList(EduUnionSchoolVO.class, pageInfo.getList());
        // 转义数据字典值
        dictHelper.valueToName(resultList, Arrays.asList(SchoolDictEnum.values()));
        for (EduUnionSchoolVO eduUnionSchoolVO : resultList) {
            eduUnionSchoolVO.setAreaName(dictHelper.getAreaNameByCode(eduUnionSchoolVO.getAreaCode()));
        }
        return PagerUtil.parsePagerVo(resultList, pageInfo);
    }

    @Override
    @OpApi(funcCode = "eduUnionSchool0002", title = "户籍跨校联合区表根据主键查询详情", funcType = FuncTypeEnum.query)
    public EduUnionSchoolVO getById(EduUnionSchoolKeyVO vo) {
        EduUnionSchool entity = eduUnionSchoolService.getById(vo.getUnionSchoolId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("查询不到详细信息!");
        }
        EduUnionSchoolVO result = Convert.convert(EduUnionSchoolVO.class, entity);
        return result;
    }

    /**
     * 保存前统一校验
     */
    @Override
    @OpApi(funcCode = "eduUnionSchool0003", title = "户籍跨校联合区表保存前校验", funcType = FuncTypeEnum.other, checkPrivilege = BoolEnum.FALSE)
    public void checkSave(EduUnionSchoolVO vo) {
        //主键为空为新增校验

        //主键不为空为修改校验
    }

    @Override
    @OpApi(funcCode = "eduUnionSchool0004", title = "户籍跨校联合区表新增", funcType = FuncTypeEnum.insert)
    @SaveOplog(
            operationType = "eduUnionSchool0004",
            operationName = "户籍跨校联合区表新增",
            dataType = "unionSchoolId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduUnionSchoolVO add(EduUnionSchoolVO vo) {
        if (vo.getYear()==null){
            vo.setYear(eduHelper.thisYear());
        }
        //保存前校验
        checkSave(vo);
        //保存数据
        if (StringUtils.isNotBlank(vo.getUnionSchoolName()) && vo.getYear() != null) {
            QueryWrapper<EduUnionSchool> queryWrapper = new QueryWrapper();
            queryWrapper.lambda().select(EduUnionSchool::getUnionSchoolName)
                    .eq(EduUnionSchool::getUnionSchoolName, vo.getUnionSchoolName())
                    .eq(EduUnionSchool::getYear, vo.getYear());
            EduUnionSchool eduUnionSchool = eduUnionSchoolService.getOne(queryWrapper);
            if (eduUnionSchool != null) {
                throw new AppException("当前年份已存在该联合区！");
            } else {
                if (StringUtils.isNotBlank(vo.getHighFlag())) {
                    vo.setHighFlag(BoolEnum.FALSE.getType());
                }
                if (StringUtils.isBlank(vo.getAreaCode())) {
                    vo.setAreaCode(SessionUtil.getAreaCode());
                }
                EduUnionSchool entity = Convert.convert(EduUnionSchool.class, vo);

                entity.setUnionSchoolId(IdUtil.simpleUUID());
                eduUnionSchoolService.save(entity);
                vo.setUnionSchoolId(entity.getUnionSchoolId());
            }
        } else {
            throw new AppException("联合区名称或年分不能为空！");
        }
        //将主键设置回vo使操作日志可以取到

        return vo;
    }

    @Override
    @OpApi(funcCode = "eduUnionSchool0005", title = "户籍跨校联合区表修改", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "eduUnionSchool0005",
            operationName = "户籍跨校联合区表修改",
            dataType = "unionSchoolId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduUnionSchoolVO edit(EduUnionSchoolVO vo) {
        if (ObjectUtils.isEmpty(vo.getUnionSchoolId())) {
            throw new AppException("传入需要修改的主键不能为空!");
        }
        EduUnionSchool oldEntity = eduUnionSchoolService.getById(vo.getUnionSchoolId());
        if (ObjectUtils.isEmpty(oldEntity)) {
            throw new AppException("查询不到需要修改的信息!");
        }
        //保存前校验
        checkSave(vo);
        //保存数据
        EduUnionSchool entity = Convert.convert(EduUnionSchool.class, vo);
        eduUnionSchoolService.updateById(entity);
        return vo;
    }

    @Override
    @OpApi(funcCode = "eduUnionSchool0006", title = "户籍跨校联合区表根据主键删除", funcType = FuncTypeEnum.delete)
    @SaveOplog(
            operationType = "eduUnionSchool0006",
            operationName = "户籍跨校联合区表删除",
            dataType = "unionSchoolId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void del(EduUnionSchoolKeyVO vo) {
        if (ObjectUtils.isEmpty(vo.getUnionSchoolId())) {
            throw new AppException("传入需要删除的数据主键不能为空!");
        }
        EduUnionSchool entity = eduUnionSchoolService.getById(vo.getUnionSchoolId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("未找到需要删除的信息!");
        }
        eduUnionSchoolService.removeById(vo.getUnionSchoolId());
    }

    @Override
    @OpApi(funcCode = "eduUnionSchool0007", title = "联合区关联学校查询", funcType = FuncTypeEnum.query)
    public PageInfo<EduUnionSchoolVO> getUnionSchoolQuery(EduUnionSchoolQueryVO vo) {
        if (StringUtils.isNotEmpty(vo.getUnionSchoolId())) {
            // 开启分页
            if (vo.getPageNum() == null || vo.getPageSize() == null) {
                //如果不传入分页参数，默认最大取1000条
                vo.setPageNum(1);
                vo.setPageSize(1000);
            }
            PageHelper.startPage(vo.getPageNum(), vo.getPageSize());

            List<EduUnionSchoolVO> list = eduUnionSchoolService.getUnionSchoolQuery(vo);
            if (CollectionUtils.isEmpty(list)) {
                // 判断是否为空，为空则返回空参数
                return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
            }
            // 不为空则获取分页结果
            PageInfo<EduUnionSchoolVO> pageInfo = new PageInfo<>(list);
            // 返回参数需要通过common层的vo实体类，用该方法可以批量转换
            List<EduUnionSchoolVO> resultList = Convert.toList(EduUnionSchoolVO.class, pageInfo.getList());
            // 转义数据字典值
            dictHelper.valueToName(resultList, Arrays.asList(SchoolDictEnum.values()));
            return PagerUtil.parsePagerVo(resultList, pageInfo);
        } else {
            return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
        }


    }


    @Override
    @OpApi(funcCode = "eduUnionSchool0008", title = "联合区关联学校删除", funcType = FuncTypeEnum.delete)
    @SaveOplog(
            operationType = "eduUnionSchool0008",
            operationName = "联合区关联学校删除",
            dataType = "unionSchoolId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void getUnionSchoolDelete(EduUnionSchoolDetailKeyVO vo) {
        if (StringUtils.isNotEmpty(vo.getUnionSchoolDetailId())) {
            if (eduUnionSchoolDetailService.getById(vo.getUnionSchoolDetailId()) != null) {
                eduUnionSchoolDetailService.removeById(vo.getUnionSchoolDetailId());
            } else {
                throw new AppException("数据已删除！");
            }
        } else {
            throw new AppException("删除参数为空!");
        }
    }

    @Override
    @OpApi(funcCode = "eduUnionSchool0009", title = "联合区关联学校新增", funcType = FuncTypeEnum.insert)
    @SaveOplog(
            operationType = "eduUnionSchool0009",
            operationName = "联合区关联学校新增",
            dataType = "unionSchoolId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduUnionSchoolVO getUnionSchoolInsert(EduUnionSchoolVO vo) {
        //保存前校验
        checkSave(vo);
        //保存数据
        if (StringUtils.isNotEmpty(vo.getUnionSchoolId())) {
            if (StringUtils.isBlank(vo.getSchoolId())) {
                vo.setSchoolId(vo.getOrgId());
            }
            int year = 0;
            if (vo.getYear() != null || vo.getYear() != 0) {

                year = vo.getYear();
            } else {
                OperationCurVO curVO = new OperationCurVO();
                curVO.setOperating("XN");
                OperationPeriodVO operationPeriodVO =
                        operationPeriodIntegration.getCurrentByOperating(curVO);
                if (operationPeriodVO != null) {
                    year = operationPeriodVO.getPeriodYear();
                } else {
                    year = DateUtil.thisYear();
                }
                vo.setYear(year);
            }
            QueryWrapper<EduUnionSchoolDetail> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().select(EduUnionSchoolDetail::getSchoolId).eq(EduUnionSchoolDetail::getUnionSchoolId, vo.getUnionSchoolId())
                    .eq(EduUnionSchoolDetail::getYear, year).eq(EduUnionSchoolDetail::getSchoolId, vo.getOrgId());
            List<EduUnionSchoolDetail> eduUnionSchoolDetails = eduUnionSchoolDetailService.list(queryWrapper);
            if (!CollectionUtil.isEmpty(eduUnionSchoolDetails)) {
                throw new AppException("当前学年学校以存在！");
            } else {
                EduUnionSchoolDetail eduUnionSchoolDetail = Convert.convert(EduUnionSchoolDetail.class, vo);
                eduUnionSchoolDetail.setStatus(BoolEnum.TRUE.getType());
                eduUnionSchoolDetail.setUnionSchoolDetailId(IdUtil.simpleUUID());
                eduUnionSchoolDetailService.save(eduUnionSchoolDetail);
            }
        } else {
            throw new AppException("新增ID为空！");
        }
        //将主键设置回vo使操作日志可以取到

        return vo;
    }

    @Override
    @OpApi(funcCode = "eduUnionSchool0010", title = "联合区复制上年度数据", funcType = FuncTypeEnum.insert)
    @Transactional
    public void init(BaseVO vo) {
        Integer year=eduHelper.thisYear();
        if(year==null){
            throw new AppException("系统年度参数未配置");
        }
        QueryWrapper<EduUnionSchool> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(EduUnionSchool::getYear,year);
        if(eduUnionSchoolService.count(queryWrapper)>0){
            throw new AppException("年度数据已存在，不能初始化");
        }
        QueryWrapper<EduUnionSchool> sndQuery=new QueryWrapper<>();
        sndQuery.lambda().eq(EduUnionSchool::getYear,year-1);
        List<EduUnionSchool> list=eduUnionSchoolService.list(sndQuery);
        if(CollectionUtils.isEmpty(list)){
            throw new AppException("上年度数据不存在存在，不能初始化");
        }
        for(EduUnionSchool eduUnionSchool:list){
            String id=eduUnionSchool.getUnionSchoolId();
            eduUnionSchool.setYear(year);
            eduUnionSchool.setUnionSchoolId(null);
            eduUnionSchoolService.save(eduUnionSchool);
            QueryWrapper<EduUnionSchoolDetail> detailQueryWrapper=new QueryWrapper<>();
            detailQueryWrapper.lambda().eq(EduUnionSchoolDetail::getUnionSchoolId,id);
            List<EduUnionSchoolDetail> detailList=eduUnionSchoolDetailService.list(detailQueryWrapper);
            if(!CollectionUtils.isEmpty(detailList)){
                for(EduUnionSchoolDetail detail:detailList){
                    detail.setUnionSchoolId(eduUnionSchool.getUnionSchoolId());
                    detail.setUnionSchoolDetailId(null);
                    detail.setYear(year);
                }
                eduUnionSchoolDetailService.saveBatch(detailList);
            }

        }
    }


}
